#include <signal.h>
#include <unistd.h>
#include "aliyun_iot_common_error.h"
#include "aliyun_iot_platform_signal.h"

typedef struct SIGNAL_DATA
{
    INT32 privateSignal;
    INT32 sysSignal;
}SIGNAL_DATA_S;

SIGNAL_DATA_S g_signalData[] =
{
    {SIGHUP_IOT,SIGHUP},
    {SIGINT_IOT,SIGINT},
    {SIGQUIT_IOT,SIGQUIT},
    {SIGILL_IOT,SIGILL},
    {SIGABRT_IOT,SIGABRT},
    {SIGFPE_IOT,SIGFPE},
    {SIGKILL_IOT,SIGKILL},
    {SIGSEGV_IOT,SIGSEGV},
    {SIGPIPE_IOT,SIGPIPE},
    {SIGALRM_IOT,SIGALRM},
    {SIGTERM_IOT,SIGTERM}
};

INT32 signal_private2system(INT32 privateSignum,INT32 *sysSignum)
{
    INT32 num = sizeof(g_signalData);
    INT32 i = 0;
    for(i = 0;i<num;i++)
    {
        if(g_signalData[i].privateSignal == privateSignum)
        {
            *sysSignum = g_signalData[i].sysSignal;
            return SUCCESS_RETURN;
        }
    }

    return FAIL_RETURN;
}

INT32 aliyun_iot_signal(INT32 signum,SIGNAL_HANDLE_TYPE_E handleType,VOID *handle)
{
    INT32 sysSignum = 0;
    if(0 != signal_private2system(signum,&sysSignum))
    {
        return FAIL_RETURN;
    }

    VOID *handleSys = 0;
    if(SIGNAL_HANDLE_SYS_DEFINE == handleType)
    {
        if(handle == (VOID *)SIG_IGN_IOT)
        {
            handleSys = (VOID *)SIG_IGN;
        }
        else
        {
            handleSys = (VOID *)SIG_DFL;
        }
    }
    else
    {
        handleSys = handle;
    }

    signal(sysSignum,handleSys);

    return SUCCESS_RETURN;
}

INT32 aliyun_iot_alarm(UINT32 seconds)
{
    alarm(seconds);
    return SUCCESS_RETURN;
}
